const axios = require("axios");
const CryptoJS = require("crypto-js");
const querystring = require("querystring");
const { _appKey, _appSecret } = require('./config/index')
// 请替换为你的实际应用ID、密钥、用户词表ID以及源语言和目标语言
const appKey = _appKey;
const key = _appSecret; // 注意：保护好您的appSecret，避免泄露

const from = "zh-CHS";
const to = "en";
const query = ["测试文本"];
const vocabId = "您的用户词表ID";

const salt = Date.now();
const curtime = Math.floor(Date.now() / 1000);

// 构建签名字符串
const str1 = appKey + truncate(query.join("")) + salt + curtime + key;
const sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);

const postData = {
  q: query,
  appKey: appKey,
  salt: salt,
  from: from,
  to: to,
  sign: sign,
  signType: "v3",
  curtime: curtime,
  vocabId: vocabId,
};
console.log(postData)
// 发起POST请求
axios
  .get(`https://openapi.youdao.com/v2/api?${querystring.stringify(postData)}`)
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error("Error:", error);
  });

// 截断函数保持不变
function truncate(q) {
  const len = q.length;
  if (len <= 20) return q;
  return q.substring(0, 10) + len + q.substring(len - 10, len);
}
